/**
 * 
 */
package com.xbjtech.shiro.realm;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.xbjtech.controller.SmsController;
import com.xbjtech.model.User;
import com.xbjtech.service.UserService;
import com.xbjtech.shiro.MobileCodeToken;

/**
 * @author Administrator
 *
 */
public class MobileCodeRealm extends AuthorizingRealm {

	@Autowired
	UserService userService;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		MobileCodeToken t = (MobileCodeToken) token;
		String mobile = (String) t.getPrincipal();
		User user = userService.selectUserByMobile(mobile);
		if (null == user) {
			throw new UnknownAccountException("用户名不存在");
		}
		if (user.getLocked().compareTo(new Integer(1)) == 0) {
			throw new LockedAccountException("用户已锁定");
		}
		Session session = SecurityUtils.getSubject().getSession();
		return new SimpleAuthenticationInfo(user, session.getAttribute(SmsController.CODE_FLAG), getName());
	}

}
